package com.anycl.customer.servlet.customer;

import com.anycl.customer.exception.CustomerException;
import com.anycl.customer.service.CustomerService;
import com.anycl.customer.service.impl.CustomerServiceImpl;
import com.anycl.customer.vo.CustomerVo;
import lombok.extern.slf4j.Slf4j;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

@WebServlet("/customer/all")
@Slf4j
public class CustomerGetAllServlet extends HttpServlet {

    private CustomerService customerService;

    @Override
    public void init() throws ServletException {
        customerService = new CustomerServiceImpl();
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        try {
            List<CustomerVo> customers = customerService.selectAllCustomer(req.getSession());
            req.setAttribute("customers", customers);
            RequestDispatcher rd = req.getRequestDispatcher("/list.jsp");
            rd.forward(req, resp);
        } catch (CustomerException e) {
            resp.getWriter().write("error: " + e.getMessage());
        }
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }

    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String method = req.getMethod();
        if (method.equalsIgnoreCase("get")) {
            doGet(req, resp);
        } else {
            doPost(req, resp);
        }
    }
}
